package app.modules.cloudpivot.controller;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.authine.cloudpivot.engine.service.impl.runtime.webservice.CXFSoapClient;
import com.authine.cloudpivot.web.api.controller.base.BaseController;

/**
 * 自定义SOAP服务请求
 *
 * @author LiuGangQiang Create in 2025/09/05
 */
@RestController
@RequestMapping("/extend/soap")
public class SoapController extends BaseController {
    private final static Logger LOG = LoggerFactory.getLogger(SoapController.class);
    private final static String SOAP_URL = "soap_url";
    public static final String DATE_TIME = "yyyy-MM-dd HH:mm:ss";
    private static final Map<String, CXFSoapClient> clientCache = new ConcurrentHashMap<>();
    private static final Object lock = new Object();

    @PostMapping(value = "/exec/{method}", produces = MediaType.APPLICATION_JSON_VALUE)
    public String exec(@PathVariable String method, @RequestBody Map<String, Object> params) {
        String url = params.get(SOAP_URL).toString();
        params.remove(SOAP_URL);
        CXFSoapClient client = getClient(url, "", "");
        try {
            Object[] res = client.invokeMethod(method, params);
            return JSON.toJSONStringWithDateFormat(res[0], DATE_TIME);
        } catch (Exception e) {
            LOG.error("===>>调用失败：{}", e.getMessage());
        }
        return "{}";
    }

    private CXFSoapClient getClient(String url, String username, String password) {
        CXFSoapClient client = clientCache.get(url);
        if (client != null) {
            return client;
        }
        synchronized (lock) {
            client = clientCache.get(url);
            if (client == null) {
                client = new CXFSoapClient(url, username, password);
                clientCache.put(url, client);
                LOG.info("===>>创建新的CXFSoapClient，URL: {}", url);
            }
            return client;
        }
    }
}
